package com.ruoyi.comparison.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.comparison.domain.TaskCheck;
import com.ruoyi.comparison.domain.TaskFile;
import com.ruoyi.comparison.domain.TaskResult;
import com.ruoyi.comparison.domain.bo.TaskFileBo;
import com.ruoyi.comparison.domain.vo.TaskCheckVo;
import com.ruoyi.comparison.domain.vo.TaskFileVo;
import com.ruoyi.comparison.mapper.TaskFileMapper;
import com.ruoyi.comparison.service.ITaskCheckService;
import com.ruoyi.comparison.service.ITaskFileService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 投招文件信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-05
 */
@RequiredArgsConstructor
@Service
public class TaskFileServiceImpl implements ITaskFileService {

    private final TaskFileMapper baseMapper;
    private final ITaskCheckService taskCheckService;

    /**
     * 查询投招文件信息
     */
    @Override
    public TaskFileVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询投招文件信息列表
     */
    @Override
    public TableDataInfo<TaskFileVo> queryPageList(TaskFileBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TaskFile> lqw = buildQueryWrapper(bo);
        Page<TaskFileVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询投招文件信息列表
     */
    @Override
    public List<TaskFileVo> queryList(TaskFileBo bo) {
        LambdaQueryWrapper<TaskFile> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TaskFile> buildQueryWrapper(TaskFileBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TaskFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStatus() != null, TaskFile::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), TaskFile::getFileName, bo.getFileName());
        lqw.eq(bo.getType() != null, TaskFile::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getBidUrl()), TaskFile::getBidUrl, bo.getBidUrl());
        lqw.eq(bo.getFileSize() != null, TaskFile::getFileSize, bo.getFileSize());
        lqw.eq(bo.getPageNum() != null, TaskFile::getPageNum, bo.getPageNum());
        return lqw;
    }

    /**
     * 新增投招文件信息
     */
    @Override
    public Boolean insertByBo(TaskFileBo bo) {
        TaskFile add = BeanUtil.toBean(bo, TaskFile.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改投招文件信息
     */
    @Override
    public Boolean updateByBo(TaskFileBo bo) {
        TaskFile update = BeanUtil.toBean(bo, TaskFile.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TaskFile entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除投招文件信息
     */
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids) {
        LambdaQueryWrapper<TaskFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TaskFile::getCheckId,ids);
        return baseMapper.delete(wrapper) > 0;
    }

    //自己设置的目录
    private static final String fileDir2 = "D:\\dev\\RuoYi-Vue-Plus\\ruoyi-admin\\fileStorage\\";
    private static final String fileDir = "/fileStorage/";
    private static final String path = "/ruoyi/server/temp";

    @Override
    @Transactional
    public String upload(Long id,MultipartFile file,int type){
        if (file.isEmpty()) {
            return null;
        }
        String fileName2=null;
        String filePath=null;
        try {
            //得到上传文件的名称
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            //得到后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name = fileName.substring(0,fileName.lastIndexOf("."));
            //校验文件后缀
            if (!(suffix.equals(".docx"))){
                throw new RuntimeException();
            }
            //首次需生成目录
            File folder = new File(fileDir2);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String formattedDate = dateFormat.format(currentDate);

            fileName2 =name+UUID.randomUUID().toString().replaceAll("-","").substring(0,6)+suffix;
            String absolutePath = fileDir2 + fileName2;
            filePath=absolutePath;
            file.transferTo(new File(absolutePath));

            TaskCheck taskCheck = new TaskCheck();
            TaskCheckVo taskCheckVo = taskCheckService.queryById(id);
            if (type==1){
                if (ObjectUtil.isEmpty(taskCheckVo.getInviteBidName())){
                    taskCheck.setInviteBidName(fileName);
                }else {
                    taskCheck.setInviteBidName(taskCheckVo.getInviteBidName()+","+fileName);
                }

                if (ObjectUtil.isEmpty(taskCheckVo.getInviteBidUrl())){
                    taskCheck.setInviteBidUrl(filePath);
                }else {
                    taskCheck.setInviteBidUrl(taskCheckVo.getInviteBidUrl()+","+filePath);
                }
            }
            taskCheck.setId(id);
            taskCheckService.updateById(taskCheck);

            TaskFile taskFile = new TaskFile();
            taskFile.setFileName(fileName);
            taskFile.setType(type);
            taskFile.setBidUrl(filePath);
            taskFile.setUrlName(fileName2);
            taskFile.setCheckId(id);
            baseMapper.insert(taskFile);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        return filePath;
    }
    @Override
    @Transactional
    public String upload1(Long id,MultipartFile file,int type){
        if (file.isEmpty()) {
            return null;
        }
        String fileName2=null;
        String filePath=null;
        try {
            //得到上传文件的名称
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            //得到后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name = fileName.substring(0,fileName.lastIndexOf("."));
            //校验文件后缀
            if (!(suffix.equals(".docx"))){
                throw new RuntimeException();
            }
            //首次需生成目录
            File folder = new File(fileDir2);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String formattedDate = dateFormat.format(currentDate);

            fileName2 =name+UUID.randomUUID().toString().replaceAll("-","").substring(0,6)+suffix;
            String absolutePath = fileDir2 + fileName2;
            filePath=absolutePath;
            file.transferTo(new File(absolutePath));

            TaskCheck taskCheck = new TaskCheck();
            if (type==0){
                taskCheck.setBidName(fileName);
                taskCheck.setBidUrl(filePath);
                taskCheck.setId(id);
                taskCheckService.updateById(taskCheck);
            }

            TaskFile taskFile = new TaskFile();
            taskFile.setFileName(fileName);
            taskFile.setType(type);
            taskFile.setBidUrl(filePath);
            taskFile.setUrlName(fileName2);
            taskFile.setCheckId(id);
            baseMapper.insert(taskFile);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        return filePath;
    }

}
